/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveWebServicesV12Helpers.Forms2
{
	/// <summary>
	/// Represents a Form in a FormsTool.
	/// </summary>
	public class Form : GrooveWebServicesV12HelpersBase
	{
		private GrooveWebServicesV12Helpers.Forms2.FormsTool m_FormsTool;
		
		protected GrooveForms2WebService.Form m_Form;

		public Form(GrooveWebServicesV12Helpers.Forms2.FormsTool i_FormsTool, GrooveWebServicesV12Helpers.GrooveForms2WebService.Form i_Form)
			: base(i_Form.Name, i_Form.URI, i_FormsTool.IdentityURL, i_FormsTool.Context)
		{
			m_FormsTool = i_FormsTool;
			m_Form = i_Form;
		}

		/// <summary>
		/// The FormsTool which contains this Form.
		/// </summary>
		public GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool
		{
			get
			{
				return m_FormsTool;
			}
		}

		/// <summary>
		/// The ID of this Form.
		/// </summary>
		public string ID
		{
			get
			{
				return m_Form.ID;
			}
		}

		/// <summary>
		/// Array of Fields used in this Form.
		/// </summary>
		public GrooveWebServicesV12Helpers.Forms2.Field[] Fields
		{
			get
			{
				System.Collections.ArrayList FieldsArrayList = new System.Collections.ArrayList();

                //  Get initialized reference to web service
				GrooveForms2WebService.GrooveForms2 FormsWebService = GrooveWebServicesV12Helpers.Forms2.FormsTool.CreateInitializedFormsWebService
					(
					m_IdentityURL,
					this.URI,
					Context
					);

				System.DateTime BeginDateTime = System.DateTime.Now;

				//  Ask service to provide fields
				GrooveForms2WebService.FormsField[] FormsFields = FormsWebService.ReadFormFields();

				if (GrooveWebServicesV12Helpers.Context.TraceEnabled)
				{
					System.TimeSpan TimeSpan = System.DateTime.Now.Subtract(BeginDateTime);
					System.Diagnostics.Debug.WriteLine("FormsWebService::ReadFormFields2, " + TimeSpan.TotalMilliseconds + " ms");
				}

				//  Create array list of fields
				foreach (GrooveForms2WebService.FormsField FormsField in FormsFields)
				{
					GrooveWebServicesV12Helpers.Forms2.Field NewField = new GrooveWebServicesV12Helpers.Forms2.Field
						(
						this,
						FormsField
						);

					FieldsArrayList.Add(NewField);
				}

				//  Return array from array list
                return (GrooveWebServicesV12Helpers.Forms2.Field[])FieldsArrayList.ToArray(typeof(GrooveWebServicesV12Helpers.Forms2.Field));
			}
		}

        /// <summary>
        /// The SchemaID of this Form.
        /// </summary>
        public string SchemaID
        {
            get
            {
                return m_Form.FormsRecordDataSet_ID;
            }
        }

        /// <summary>
        /// If true, Groove saves the existing version of the record when it is updated. 
        /// The existing version of the record is assigned a new RecordID and is saved as a child of the new updated record
        /// </summary>
        public bool MaintainRecordVersionHistory
        {
            get
            {
                return m_Form.MaintainRecordVersionHistory;
            }
        }

        /// <summary>
        /// Returns the kind of form. In Groove 4.0, this element has a value of either 
        /// "InfoPath" or "DHTML", but may have additional values in future versions of Groove
        /// </summary>
        public string Type
        {
            get
            {
                return m_Form.Type;
            }
        }

        /// <summary>
        /// Specifies whether the Forms tool designer has specified that the form is used 
        /// to create response records
        /// </summary>
        public bool IsResponse
        {
            get
            {
                return m_Form.IsResponse;
            }
        }

        /// <summary>
        /// If true, the form has been marked for deletion but not yet deleted to allow 
        /// access to existing records created with that form. When a form is marked for 
        /// deletion, you cannot create new records with that form using the CreateRecords 
        /// operation, but you can query for, read, update, and delete the existing records. 
        /// Once all existing records created with that form have been deleted, Groove 
        /// deletes the form.
        /// </summary>
        public bool IsDeleted
        {
            get
            {
                return m_Form.IsDeleted;
            }
        }

		#region GrooveWebServicesV12HelpersBase Implementation

		public override string BindableURL
			{
			get
			{
				if (System.String.IsNullOrEmpty(m_BindableURL))
					m_BindableURL = m_FormsTool.BindableURL + "/Form#" + this.ID;

				return m_BindableURL;
			}
		}

		public override object BindToObject(ref string[] i_URLParts, int i_URLPartIndex)
		{
			object BindResult = null;
			string RelativeURL = i_URLParts[i_URLPartIndex];
			string[] RelativeURLParts = RelativeURL.Split(new char[]{'#'});

			string ObjectType = RelativeURLParts[0];

			if (ObjectType == "Field")
			{
				string FieldURI = m_FormsTool.URI + "/DataModelDelegate/FieldID=" + RelativeURLParts[1];
				FieldURI = FieldURI.Replace("Tools/", "Forms/");

				try
				{
					//  ---------------------------------------------------------------------------------------
					//  HACK ALERT:  Since there is no ReadField method, must read all fields and do uri match

					    foreach (GrooveWebServicesV12Helpers.Forms2.Field Field in this.Fields)
					    {
						    if (Field.URI == FieldURI)
						    {
							    BindResult = Field;
							    break;
						    }
					    }

					//  ---------------------------------------------------------------------------------------
				}
				catch (System.Exception Exception)
				{
					throw new System.Exception("Unable to find Field '" + FieldURI +"' (" + Exception.Message + ")");
				}
			}
			else
				throw new System.Exception("Unknown form url part - '" + ObjectType + "'");

			return BindResult;
		}

		#endregion
	}

}
